<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\common\model\Api;
use app\admin\admin\Base;
use app\common\model\Order;
use app\goods\model\Cart;
use app\user\export\IndexExport;
use app\user\model\Address as UserAddress;
use app\user\model\MoneyLog;
use app\user\model\User as UserModel;
use service\ApiReturn;
use service\Format;
use think\Db;
use think\facade\Cookie;

/**
 * 会员主表控制器
 * @package app\User\admin
 */
class Index extends Base
{
    /**
     * 会员主表列表
     * @return mixed
     * @throws \think\exception\DbException
     * @author 似水星辰 [2630481389@qq.com]
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 查询
        $map = input('param.');


        $search_fields = [
            ['keywords', lang('昵称、电话、UID'), 'text'],
            ['time', lang('日期选择'), 'daterange'],
        ];

        $order = ['id' => 'desc'];

        $data_list = UserModel::search($map, $order);
        if ($map['export'] == 1) {
            $Export = new IndexExport;
            return $Export->export($map);
        }
        foreach ($data_list as $k => &$item) {
            $item['order_num'] = Order::where('user_id', $item['id'])->count();
            $order_time = Order::where('user_id', $item['id'])
                ->order('aid', 'desc')
                ->value('create_time');
            $item['order_time'] = $order_time ? date('Y-m-d', $order_time) : '暂无';
        }
        unset($item);
        $fields = [
            ['id', 'ID'],
            ['head_img', lang('头像'), 'picture'],
            ['user_nickname', lang('用户信息'), 'callback', function ($value, $data) {
                $string = "";
                $string .= "昵称：<a  href=" . url('info', ['ids' => $data['id'], 'layer' => 1])
                    . " class='mr5 comment' data-toggle='dialog-right'>{$value}</a>" . "<br>";
                $string .= "电话：" . $data['mobile'] . "<br>";
                return $string;
            }, '__data__'],

            ['sex', lang('性别'), 'callback', function ($value) {
                return $this->getUserSex($value);
            }],
            ['total_consumption_money', lang('累计消费金额')],
            ['freeze_money', lang('冻结金额')],
            ['order_num', lang('下单次数')],
            ['order_time', lang('最后一次下单时间')],
            ['id', lang('优惠券数量'), 'callback', function ($value) {
                return $this->coupon_num($value);
            }],
            ['status', lang('状态'), 'status'],
            ['create_time', lang('注册时间')],
            ['right_button', lang('操作'), 'btn']
        ];
        //是否显示导出excel按钮 1显示
        $this->assign('excel_show', 1);
        if (count($data_list) <= 0) {
            $this->bottom_button_select = [];
        }
        return Format::ins()
            ->setOrder('user_money,score,total_consumption_money,count_score')
            ->addColumns($fields)//设置字段
            ->setTopSearch($search_fields)
            ->hideCheckbox()//隐藏多选框
            ->setTopButtons($this->top_button,['add'])
            ->setRightButtons($this->right_button, ['delete'])
            ->setData($data_list)//设置数据
            ->fetch();//显示
    }

    /*
     * 获取优惠券数量
     *
     */
    public function coupon_num($user_id)
    {
        return Db::name("operation_coupon_record")->where([
            ['user_id', '=', $user_id],
            ['status', '=', 1],
            ['start_time', '<=', time()],
            ['end_time', '>=', time()]
        ])->count();
    }

    public function user_delete($ids)
    {
        Db::startTrans();
        try {
            Db::name("user")->where(['id' => $ids])->setField('is_delete', 1);
            Db::name("user_info")->where(['user_id' => $ids])->delete();    //用户信息做物理删除
            //清除缓存
            Api::clearUserCache($ids);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(lang('删除失败'));
        }
        $this->success(lang('删除成功'));
    }

    public function setStatus($type = '')
    {
        $data = input("param.");
        $ids = $data['ids'];
        $type = $data['type'] ?? $data['action'];
        $ids = (array)$ids;

        empty($ids) && $this->error(lang('缺少主键'));
        $result = false;
        switch ($type) {
            case 'disable': // 禁用
                $result = UserModel::where('id', 'IN', $ids)->setField('status', 0);
                Api::clearUserCache($ids[0]);
                action_log('user_disable', 'user', 0, UID, lang('批量禁用用户') . 'ID:' . $ids);
                break;
            case 'enable': // 启用
                $result = UserModel::where('id', 'IN', $ids)->setField('status', 1);
                Api::clearUserCache($ids[0]);
                action_log('user_enable', 'user', 0, UID, lang('批量启用用户') . 'ID:' . $ids);
                break;
            case 'delete': // 删除
                $result = UserModel::where('id', 'IN', $ids)->setField('is_delete', 1);
                action_log('user_delete', 'user', 0, UID, lang('批量删除商品') . 'ID:' . $ids);
                break;
            default:
                $this->error(lang('非法操作'));
                break;
        }

        if (false !== $result) {
            // \Cache::clear();
            // 记录行为
            action_log('admin_user_' . $type, 'user', $ids, UID, 'ID：' . implode('、', $ids));
            return ApiReturn::r(1, [], lang('操作成功'));
        } else {
            return ApiReturn::r(0, [], lang('操作失败'));
        }
    }


    /*
     * 会员购物车
     *
     */
    public function cart($data)
    {
        $pagesize = $data['pagesize'];
        $list = Cart::where(['user_id' => $data['user_id']])->order('create_time DESC')
            ->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     * 会员订单
     *
     */
    public function order($data)
    {
        $pagesize = $data['pagesize'];
        $list = Order::where(['user_id' => $data['user_id']])
            ->order('create_time DESC')
            ->paginate($pagesize, false, ['query' => request()->param()])
            ->each(function (&$v) {
                $v['status'] = Order::$order_status[$v['status']];
                return $v;
            });
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     *
     *会员地址
     */
    public function address($data)
    {
        $pagesize = $data['pagesize'];
        $list = UserAddress::where(['user_id' => $data['user_id']])
            ->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     *
     * 会员充值
     *
     */
    public function recharge($data)
    {
        $pagesize = $data['pagesize'];
        $list = MoneyLog::where([
            'user_id' => $data['user_id'],
            'change_type' => 1
        ])
            ->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     *
     * 提现
     *
     */
    public function withdrawal($data)
    {
        $pagesize = $data['pagesize'];
        $list = MoneyLog::where([
            'user_id' => $data['user_id'],
            'change_type' => 4
        ])
            ->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     * 积分
     *
     */
    public function integral($data)
    {
        $pagesize = $data['pagesize'];
        $list = Db::name("user_score_log")->where([
            'user_id' => $data['user_id'],
        ])
            ->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     * 浏览记录
     *
     */
    public function visit($data)
    {
        $pagesize = $data['pagesize'];
        $list = Db::name("user_collection")->where([
            'user_id' => $data['user_id'],
            'type' => 3
        ])->order("create_time DESC")->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }

    /*
     *
     * 收藏记录
     *
     */
    public function collection($data)
    {
        $pagesize = $data['pagesize'];
        $list = Db::name("user_collection")->where([
            'user_id' => $data['user_id'],
            'type' => 1
        ])->order("create_time DESC")->paginate($pagesize, false, ['query' => request()->param()]);
        $pages = $list->render();
        $result = [
            'list' => $list,
            'pages' => $pages,
        ];
        return $result;
    }


    /*
     * 会员详情
     */
    public function info()
    {
        $ids = input('param.ids');
        $page = input('param.page');
        $model = input('param.model');
        $pagesize = input('param.pagesize');
        $info = UserModel::where(['id' => $ids])->find();
        if (!$info) {
            $this->error(lang('信息不存在'));
        }
        $info['head_img'] = get_file_url($info['head_img']);
        if (strpos($info['head_img'], 'images/none.png') !== false) {
            $info['head_img'] = config('web_site_domain') . '/static/admin/images/benben.png';
        }

        $info['user_type'] = $this->getMember($info['user_type']);
        $info['sex'] = $this->getUserSex($info['sex']);
        $info['coupon_num'] = $this->coupon_num($ids);

        $this->assign('info', $info);

        $where = [
            'user_id' => $ids,
            'page' => $page,
            'pagesize' => $pagesize
        ];


        if ($model == "address") {
            //会员地址
            $address = $this->address($where);
            $this->assign('address', $address['list']);
            $this->assign('address_pages', $address['pages']);
        } else if ($model == "order") {
            //会员订单
            $order = $this->order($where);
            $this->assign('order', $order['list']);
            $this->assign('order_pages', $order['pages']);
        } else if ($model == "recharge") {
            //会员充值
            $order_recharge = $this->recharge($where);
            $this->assign('recharge', $order_recharge['list']);
            $this->assign('recharge_pages', $order_recharge['pages']);
        } else if ($model == "withdrawal") {
            //会员提现
            $withdrawal = $this->withdrawal($where);
            $this->assign('withdrawal', $withdrawal['list']);
            $this->assign('withdrawal_pages', $withdrawal['pages']);
        } else if ($model == "visit") {
            //浏览记录
            $visit = $this->visit($where);
            $this->assign('visit', $visit['list']);
            $this->assign('visit_pages', $visit['pages']);
        } else if ($model == "collect") {
            //收藏记录
            $collection = $this->collection($where);
            $this->assign('collection', $collection['list']);
            $this->assign('collection_pages', $collection['pages']);
        } else {
            $model = "cart";
            //会员购物车
            $cart = $this->cart($where);
            foreach ($cart['list'] as &$v) {
                $v['goods_thumb'] = get_file_url($v['goods_thumb']);
            }
            $this->assign('cart', $cart['list']);
            $this->assign('cart_pages', $cart['pages']);
        }
        $this->assign('model', $model);
        return $this->fetch();
    }

    public function getMember($user_type)
    {
        $data = ['0' => lang('普通会员'), '1' => lang('白银会员'), '2' => lang('黄金会员')];
        return $data[$user_type];
    }

    public function getUserSex($sex)
    {
        $data = ['0' => lang('保密'), '1' => lang('男'), '2' => lang('女')];
        return $data[$sex];
    }

    /**
     * 新增
     * @return mixed
     * @author 似水星辰 [2630481389@qq.com]
     */
    public function add()
    {

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $birthday = strtotime($data['birthday']);
            if ($birthday > time()) {
                exception(lang('生日不能超过当前时间'));
            }
            $data['birthday'] = $birthday;

            // 验证
            $result = $this->validate($data, 'User');
            if (true !== $result) {
                $this->error($result);
            }
            // 启动事务
            Db::startTrans();
            try {
                //验证手机号是否已经存在
                $find = UserModel::where(['mobile' => $data['mobile']])->find();
                if ($find) {
                    exception(lang('手机号已存在'));
                }
                $result = UserModel::create($data);
                $id = $result->id;
                if (!$id) {
                    exception(lang('新增会员失败'));
                }
                // 新增会员附加信息
                $userinfo = Db::name('user_info')->insert(['user_id' => $id, 'invite_code' => 'IC00' . $id]);
                if (!$userinfo) {
                    exception(lang('新增会员附加信息失败'));
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success(lang('新增成功'), cookie('__forward__'));
        }

        $fields = [
            ['type' => 'text', 'name' => 'mobile', 'title' => lang('手机号')],
            ['type' => 'password', 'name' => 'password', 'title' => lang('密码')],
            ['type' => 'text', 'name' => 'user_nickname', 'title' => lang('昵称')],
            ['type' => 'text', 'name' => 'user_name', 'title' => lang('姓名')],
            ['type' => 'image', 'name' => 'head_img', 'title' => lang('头像')],
            ['type' => 'date', 'name' => 'birthday', 'title' => lang('生日'), 'tips' => '', 'attr' => ''],
            ['type' => 'radio', 'name' => 'sex', 'title' => lang('性别'), 'tips' => '', 'attr' => '', 'extra' => [lang('保密'), lang('男'), lang('女')], 'value' => '0'],
            ['type' => 'text', 'name' => 'user_email', 'title' => lang('邮箱')],

        ];
        $this->assign('page_title', lang('新增会员'));
        $this->assign('form_items', $fields);
        return $this->fetch('admin@public/add');
    }

    /**
     * 编辑
     * @param null $id 会员主表id
     * @return mixed
     * @author 似水星辰 [2630481389@qq.com]
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error(lang('缺少参数'));
        }

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $data['birthday'] = strtotime($data['birthday']);
            // 如果没有填写密码，则不更新密码
            if ($data['password'] == '') {
                unset($data['password']);
            }

            // 验证
            $result = $this->validate($data, 'User.edit');
            if (true !== $result) {
                $this->error($result);
            }
            $UserModel = new UserModel();
            if ($UserModel->allowField(['user_nickname', 'password', 'head_img'])->update($data)) {
                $this->success(lang('编辑成功'), cookie('__forward__'));
            } else {
                $this->error(lang('编辑失败'));
            }
        }

        $info = UserModel::get($id);
        $fields = [
            ['type' => 'hidden', 'name' => 'id'],
            ['type' => 'text', 'name' => 'mobile', 'title' => lang('手机号'), 'tips' => '', 'attr' => ''],
            ['type' => 'password', 'name' => 'password', 'title' => lang('重置密码'), 'tips' => '', 'attr' => ''],
            ['type' => 'text', 'name' => 'user_nickname', 'title' => lang('昵称'), 'tips' => '', 'attr' => ''],
            ['type' => 'text', 'name' => 'user_name', 'title' => lang('姓名'), 'tips' => '', 'attr' => ''],
            ['type' => 'image', 'name' => 'head_img', 'title' => lang('头像'), 'tips' => '', 'attr' => ''],
            ['type' => 'date', 'name' => 'birthday', 'title' => lang('生日'), 'tips' => '', 'attr' => ''],
            ['type' => 'radio', 'name' => 'sex', 'title' => lang('性别'), 'tips' => '', 'attr' => '', 'extra' => [lang('保密'), lang('男'), lang('女')], 'value' => '0'],
            ['type' => 'text', 'name' => 'user_email', 'title' => lang('邮箱')],
        ];
        $this->assign('page_title', lang('编辑会员信息'));
        $this->assign('form_items', $this->setData($fields, $info));
        return $this->fetch('admin@public/edit');
    }

    /*
     * 语言切换
     *
     */
    public function lang()
    {
        $language = request()->param("language");
        Cookie::set("language", $language, 24 * 60 * 60);
    }
}
